﻿#region "Copyright (C) Lenny Granovsky. 2011-2013"
//    This library provides extended cache capabilities to the ASP.NET applications.
//
//                Copyright (C) Lenny Granovsky. 2011-2013. 
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//    This program comes with ABSOLUTELY NO WARRANTY.
//    This is free software, and you are welcome to redistribute it
//    under certain conditions;
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace FlexiCache
{
    /// <summary>
    /// Class provides functionality for Cache on Demand. It implements the ICacheOnDemandProvider interface. 
    /// It uses the MongoDBCacheProviderBase as an underlying storage connector. 
    /// </summary>
    /// <remarks>This class is not intended to be used directly. The RuntimeContext should be used instead.</remarks>
    public class CacheOnDemandProvider : ExternalCacheProviderBase, ICacheOnDemandProvider, IDisposable
    {
        private const string ApplicationContextCacheOnDemandStorageMemorySlotName = "RuntimeContextApplicationCacheOnDemandStorage";

        /// <summary>
        /// Gets or sets a boolean indication where or not out-of-proc CacheOnDemand is enabled or not.
        /// </summary>
        public bool IsEnabled { get; set; }

        private static ApplicationObjectCollection ThreadApplicationData
        {
            get
            {
                LocalDataStoreSlot slot = Thread.GetNamedDataSlot(ApplicationContextCacheOnDemandStorageMemorySlotName);
                object tmp = Thread.GetData(slot);
                if (tmp != null)
                    return (ApplicationObjectCollection)tmp;
                Thread.SetData(slot, new ApplicationObjectCollection());
                tmp = Thread.GetData(slot);
                if (tmp != null)
                    return (ApplicationObjectCollection)tmp;
                throw new Exception("Unable to initialize ApplicationObjectCollection in thread memory data slot.");
            }
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public CacheOnDemandProvider()
            : base(CachingConfiguration.Current.CacheOnDemandConfig)
        {
        }

        /// <summary>
        /// Method adds data into the cache with specified key and expiration.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        /// <param name="utcExpiry">Expiration time (UTC).</param>
        /// <returns>Returns cached object.</returns>
        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            this.Set(key, entry, utcExpiry);
            return entry;
        }

        /// <summary>
        /// Method gets a data from the cache using specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <returns>Returns cached object.</returns>
        public override object Get(string key)
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (this.IsEnabled)
                    return base.Get(key);
                else
                    return System.Web.HttpContext.Current.Cache.Get(key);
            }
            else
                return ThreadApplicationData.Get(key);
        }

        /// <summary>
        /// Method determines whether a cache entry for specified key exists in the cache.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <returns>Returns true if the cache contains a cache entry whose key matches key; otherwise, false.</returns>
        public override bool Contains(string key)
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (this.IsEnabled)
                    return base.Contains(key);
                else
                    return System.Web.HttpContext.Current.Cache.Get(key) != null;
            }
            else
                return ThreadApplicationData.ContainsAndNotNull(key);
        }

        /// <summary>
        /// Method removes data from the cache using specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        public override void Remove(string key)
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (this.IsEnabled)
                    base.Remove(key);
                else
                    System.Web.HttpContext.Current.Cache.Remove(key);
            }
            else
                ThreadApplicationData.Remove(key);
        }

        /// <summary>
        /// Method sets (updates or adds) data into the cache with specified key and expiration.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        /// <param name="utcExpiry">Expiration time (UTC).</param>
        public override void Set(string key, object entry, DateTime utcExpiry)
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (this.IsEnabled)
                {
                    base.Set(key, entry, utcExpiry);
                    return;
                }
                if (entry == null)
                    System.Web.HttpContext.Current.Cache.Remove(key);
                else
                    System.Web.HttpContext.Current.Cache.Insert(key, entry, null, utcExpiry, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            else
                ThreadApplicationData.Set(key, entry);
        }
    }
}
